package com.cqeec.bootdemo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqeec.bootdemo.common.R;
import com.cqeec.bootdemo.entity.User;
import com.cqeec.bootdemo.service.UserService;
import com.cqeec.bootdemo.util.ValidateCodeUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 验证码发送
     */
    @PostMapping("/sendMsg")
    public R<String> sendMSG(@RequestBody User user, HttpServletRequest request){
        log.info("发送验证码,手机号{}",user.getPhone());
        //制造验证码
        String code= ValidateCodeUtils.generateValidateCode()+"";
        log.info("验证码:{}",code);
        request.getSession().setAttribute(user.getPhone(),code);
        return R.success("验证码发送成功");
    }
    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpServletRequest request){
        log.info("用户登录：{}",map);
        //用户页面上传来的数据
        String phone=(String) map.get("phone");
        String code=(String) map.get("code");
        log.info("用户手机号：{}",phone);
        log.info("用户登录：{}",code);
        //登录判断，判断输入的数据与session中的数据是否一致
        String codeS = (String) request.getSession().getAttribute(phone);
        log.info("session中的验证码：{}",codeS);
        if(codeS==null){
            return R.error("验证码已失效");
        }
        if(!codeS.equals(code)){
            return R.error("验证码错误");
        }
        //判断这个用户之前登录过没有
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user1=userService.getOne(wrapper);
        if(user1==null){
            User user=new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
            request.getSession().setAttribute("user",user.getId());
            return R.success(user);
        }
        request.getSession().setAttribute("user",user1.getId());
        return R.success(user1);
    }
    @PostMapping("loginout")
    public R<String> loginout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
